import flvjs from 'flv.js'

export default {
  
  playVideo (flv_url, videoElementId) {
    let player = null
    if (flvjs.isSupported()) {
      if (player) {
        player.pause();
        player.unload();
        player.detachMediaElement();
        player.destroy();
        player = null;
      }
      let videoElement = document.getElementById(videoElementId)
      player = flvjs.createPlayer(
        {
          // 创建一个新的flv播放器对象
          type: 'flv',
          isLive: true,
          url: flv_url,

          cors: true,
          withCredentials: false,
          hasAudio: false,
        },
        {
          enableWorker: false, // 不启用分离线程
          autoCleanupSourceBuffer: true,
          autoCleanupMaxBackwardDuration: 5,
          autoCleanupMinBackwardDuration: 2,
          enableStashBuffer: false,
          fixAudioTimestampGap: false,
          stashInitialSize: 128,
          reuseRedirectedURL: true
        }
      )
      player.attachMediaElement(videoElement)
      player.load() // 载入视频
      var promise = player.play() // 播放视频，如果不想要自动播放，去掉本行
      
      // The play() request was interrupted by a call to pause() 还没加载完就播放 会出现这个错误
      if (promise) {
        promise.then(() => {
          player.play()
        })
      }
    }
    return player
  },

  /**
   * 播放视频
   * @param {*} flv_url 
   * @param {*} videoElement 
   * @returns 
   */
  playVideoElement (flv_url, videoElement) {
    let player = null
    if (flvjs.isSupported()) {
      if (player) {
        player.pause();
        player.unload();
        player.detachMediaElement();
        player.destroy();
        player = null;
      }
      player = flvjs.createPlayer(
        {
          // 创建一个新的flv播放器对象
          type: 'flv',
          isLive: true,
          url: flv_url,

          cors: true,
          withCredentials: false,
          hasAudio: false,
        },
        {
          enableWorker: false,
          autoCleanupSourceBuffer: true,
          autoCleanupMaxBackwardDuration: 5,
          autoCleanupMinBackwardDuration: 2,
          enableStashBuffer: false,
          fixAudioTimestampGap: false,
          stashInitialSize: 128,
          reuseRedirectedURL: true
        }
      )
      player.attachMediaElement(videoElement)
      player.load() // 载入视频
      var promise = player.play() // 播放视频，如果不想要自动播放，去掉本行
      
      // The play() request was interrupted by a call to pause() 还没加载完就播放 会出现这个错误
      if (promise) {
        promise.then(() => {
          player.play()
        })
      }
    }
    return player
  },

  stopPlayer (player) {
    if (player) {
      player.pause();
      player.unload();
      player.detachMediaElement();
      player.destroy();
      player = null;
    }
  }
}
